package com.xul.crowd.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xul.crowd.constant.CrowdConstant;
import com.xul.crowd.entity.Admin;
import com.xul.crowd.entity.AdminExample;
import com.xul.crowd.exception.LoginAcctAlreadyInUseException;
import com.xul.crowd.exception.LoginAcctAlreadyInUseForUpdateException;
import com.xul.crowd.exception.LoginFailedException;
import com.xul.crowd.mapper.AdminMapper;
import com.xul.crowd.service.AdminService;
import com.xul.crowd.util.CrowdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author xul
 * @create 2021-07-22 18:48
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void save(Admin admin) {
        String userPswd = admin.getUserPswd();
        // String userPswdMd5 = CrowdUtil.md5(userPswd);

        /*
         该成带盐值得加密
         */
        String encode = passwordEncoder.encode(userPswd);
        admin.setUserPswd(encode);

        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
        String createTime = format.format(date);
        admin.setCreateTime(createTime);

        try {
            adminMapper.insert(admin);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                throw new LoginAcctAlreadyInUseException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }
    }

    @Override
    public List<Admin> findAll() {
        List<Admin> adminList = adminMapper.selectByExample(new AdminExample());
        return adminList;
    }

    /**
     * 用户登录接口
     *
     * @param loginAcct
     * @param userPswd
     * @return
     */
    @Override
    public Admin getAdminLoginAcct(String loginAcct, String userPswd) {
        // 创建条件构造器
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        // 封装条件
        criteria.andLoginAcctEqualTo(loginAcct);
        List<Admin> adminList = adminMapper.selectByExample(adminExample);
        if (adminList == null || adminList.size() == 0) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        if (adminList.size() > 1) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_ERROR_LOGIN_NOT_UNIQUE);
        }
        Admin admin = adminList.get(0);
        if (admin == null) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        String userPswdDB = admin.getUserPswd();
        String userPswdMd5 = CrowdUtil.md5(userPswd);
        if (!Objects.equals(userPswdDB, userPswdMd5)) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        return admin;
    }

    /**
     * 管理员条件查询带分页
     *
     * @param keyword
     * @param page
     * @param limit
     * @return
     */
    @Override
    public PageInfo<Admin> getPageInfo(String keyword, Integer page, Integer limit) {
        // 1.调用PageHelper的静态方法开启分页功能
        PageHelper.startPage(page, limit);
        List<Admin> adminList = adminMapper.selectAdminByKeyword(keyword);
        // 2.封装到PageInfo对象中去
        PageInfo<Admin> pageInfoModel = new PageInfo<>(adminList);
        return pageInfoModel;
    }

    /**
     * 根据id删除管理员信息
     *
     * @param adminId
     */
    @Override
    public void remove(Integer adminId) {
        adminMapper.deleteByPrimaryKey(adminId);
    }

    /**
     * 修改管理员数据 让表单回显
     *
     * @param adminId
     * @return
     */
    @Override
    public Admin getAdminById(Integer adminId) {
        return adminMapper.selectByPrimaryKey(adminId);
    }

    /**
     * 表单回显后更新管理员信息
     *
     * @param admin
     */
    @Override
    public void update(Admin admin) {

        try {
            // 表示有选择的更新,对于null的字段不更新
            adminMapper.updateByPrimaryKeySelective(admin);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                throw new LoginAcctAlreadyInUseForUpdateException(CrowdConstant.MESSAGE_LOGIN_ERROR_LOGIN_NOT_UNIQUE);
            }
        }
    }

    /**
     * 理员实现对角色的分配 保存选中的角色到数据库(提交表单)
     *
     * @param adminId
     * @param roleIdList
     */
    @Override
    public void saveAdminRoleRelationship(Integer adminId, List<Integer> roleIdList) {
        // 1.根据adminId删除旧的关联关系数据
        adminMapper.deleteOldRelationship(adminId);
        // 2.根据roleIdList和adminId保存新的关系联系
        if (roleIdList != null && roleIdList.size() > 0) {
            adminMapper.insertNewRelationship(adminId, roleIdList);
        }

    }

    /**
     * 根据用户名查询用户信息
     *
     * @param loginAcct
     * @return
     */
    @Override
    public Admin getAdminByLoginAcct(String loginAcct) {
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andLoginAcctEqualTo(loginAcct);
        List<Admin> adminList = adminMapper.selectByExample(adminExample);
        Admin admin = adminList.get(0);
        return admin;
    }
}
